#include <all.h>

extern uint8_t vol_cu_sence[2];

void adc_init()
{
	ADCCFG = 0x2f;
	ADC_CONTR |= 0x80;
}

uint16_t get_adc_dat(uint8_t chanel)
{
	uint16_t i = 0; // 局部变量
	uint8_t x;
	adc_init();
	ADC_CONTR &= 0xf0;
	ADC_CONTR |= chanel | 0x40;
	_nop_();
	_nop_();
	while (!(ADC_CONTR & 0x20))
		;
	ADC_CONTR &= ~0x20;
	ADC_RES = ADC_RESL = 0;

	for (x = 0; x < 2; x++)
	{
		ADC_CONTR &= 0xf0;
		ADC_CONTR |= chanel | 0x40;
		_nop_();
		_nop_();
		while (!(ADC_CONTR & 0x20))
			;
		ADC_CONTR &= ~0x20;
		i += ADC_RES << 8 | ADC_RESL;
		ADC_RES = ADC_RESL = 0;
	}
	i >>= 1;
	return i;
}

float get_vol()
{
	uint16_t x;
	float i = 0;
	uint8_t j;
	uint8_t ch;
	x = get_adc_dat(2);
	if (x)
		ch = 2;
	else
		ch = 3;

	for (j = 0; j < 10; j++)
	{
		x = get_adc_dat(ch);
		i += x * 0.000366700197269539;
	}
	if (i > 0.008)
		i -= 0.008;
	if (ch == 3)
		i = -i;
	return i;
}

float get_cu(uint8_t ch)
{
	uint16_t x;
	float i = 0;
	uint16_t j;

	if (ch == 1)
	{
		x = get_adc_dat(4);
		if (x)
		{
			ch = 4; /// f1fu
		}
		else
		{
			ch = 5; // f1zheng
		}
	}
	else
	{
		x = get_adc_dat(6);
		if (x)
			ch = 6; // f2fu
		else
			ch = 7; // f2zheng
	}

	for (j = 0; j < 100; j++)
	{
		x = get_adc_dat(ch);
		i += x * 0.24462988476953907; //  1/4096*2.5/24.95*100000   24.46298847695390782
	}

	if (ch == 4 || ch == 6)
		i = -i;
	if (ch == 4 || ch == 5)
	{
		i += (float)vol_cu_sence[0] * 24.46298847695390782;
		i -= 3.4 * (float)vol_cu_sence[0];
	}
	if (ch == 7 || ch == 6)
	{
		i += (float)vol_cu_sence[1] * 24.46298847695390782;
		i -= 3.4 * (float)vol_cu_sence[1];
	}

	i += 34;

	return i;
}
